package com.ysz.component.statisticstime;

import org.apache.commons.lang3.StringUtils;

import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName StatisticsTime
 * @Description 时间统计
 * @Data 10:17
 * @Version 1.0
 * @Author ysz
 */
public class StatisticsTime implements Closeable {

    private static final ConcurrentHashMap<String, List<TaskInfo>> TASK_RESULT_MAP = new ConcurrentHashMap<>();

    private String stopTaskName;

    public StatisticsTime(String stopTaskName) {
        this.stopTaskName = stopTaskName;
    }

    public StatisticsTime() {
    }

    public void start(String taskName) {
        if (StringUtils.isEmpty(taskName)) {
            throw new RuntimeException("taskName must not null");
        }
        this.stop(taskName);
        TaskInfo taskInfo = new TaskInfo(taskName, null, System.currentTimeMillis());
        ArrayList<TaskInfo> taskInfosArray = new ArrayList<TaskInfo>() {{
            add(taskInfo);
        }};
        //taskInfosArray == t2
        //t1 oldValue
        //when the map not contains taskName then will put k:taskName v:taskInfosArray and not execute lambda
        TASK_RESULT_MAP.merge(taskName, taskInfosArray, (t1, t2) -> {
            t1.addAll(t2);
            return t1;
        });
    }

    public String start() {
        String taskName = Thread.currentThread().getName();
        this.start(taskName);
        return taskName;
    }


    public void stop(String taskName) {
        List<TaskInfo> taskInfos = TASK_RESULT_MAP.get(taskName);
        if (StringUtils.isEmpty(taskName)) {
            throw new RuntimeException("taskName must not null");
        }
        if (Objects.nonNull(taskInfos) && taskInfos.size() > 0) {
            TaskInfo taskInfo = taskInfos.get(taskInfos.size() - 1);
            if (Objects.isNull(taskInfo.getTotalTim())) {
                taskInfo.setTotalTim(System.currentTimeMillis() - taskInfo.getStartTim());
                System.out.println("============================");
                System.out.println("任务===>" + taskInfo.getTaskName() + " 耗时统计： " + taskInfo.getTotalTim() + "MS");
                System.out.println("============================");
            }
        }
    }


    public String stop() {
        String taskName = Thread.currentThread().getName();
        this.stop(taskName);
        return taskName;
    }


    @Override
    public void close() throws IOException {
        this.stop(this.stopTaskName);
    }
}
